<template>
  <el-form
    ref="userForm"
    class="info-form"
    :model="userForm"
    label-width="100px">
    <h3>用户资料</h3>
    <el-row>
      <el-form-item label="用户名">
        <el-input v-model="userForm.username" :disabled="true"></el-input>
      </el-form-item>
    </el-row>
    <el-row>
      <el-col :span="20">
        <el-form-item label="密码">
          <el-input type="password" v-model="userForm.password" :disabled="true"></el-input>
        </el-form-item>
      </el-col>
      <el-button type="primary" @click="passVisible = true">更改</el-button>
    </el-row>
    <el-dialog
      title="密码修改"
      :visible.sync="passVisible"
      width="30%"
    >
      <el-form
        ref="changePassForm"
        class="change-form"
        :model="changePassForm"
        :rules="changePassRules"
        label-width="80px"
      >
        <el-form-item label="旧密码" prop="oldPass">
          <el-input type="password"
                    v-model="changePassForm.oldPass"
                    autocomplete="off"
                    prefix-icon="el-icon-key"
                    placeholder="请输入旧密码"
                    show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass">
          <el-input type="password"
                    v-model="changePassForm.newPass"
                    autocomplete="off"
                    prefix-icon="el-icon-key"
                    placeholder="请输入新密码"
                    show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password"
                    v-model="changePassForm.checkPass"
                    autocomplete="off"
                    prefix-icon="el-icon-key"
                    placeholder="请再次输入新密码"
                    show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="formSubmit('changePassForm')">更改</el-button>
        <el-button @click="reset">取 消</el-button>
      </span>
    </el-dialog>
    <el-row>
      <el-col :span="20">
        <el-form-item label="电话">
          <el-input v-model="userForm.phone" :disabled="true"></el-input>
        </el-form-item>
      </el-col>
      <el-button type="primary" @click="phoneVisible = true">更改</el-button>
    </el-row>
    <el-dialog
      title="电话更改"
      :visible.sync="phoneVisible"
      width="30%"
    >
      <el-form
        ref="changePhoneForm"
        class="change-form"
        :model="changePhoneForm"
        :rules="changePhoneRules"
        label-width="80px"
      >
        <el-form-item label="电话" prop="phone">
          <el-input type="text"
                    v-model="changePhoneForm.phone"
                    autocomplete="off"
                    prefix-icon="el-icon-mobile"
                    placeholder="请输入电话号码"
                    style="width: 100%"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="formSubmit('changePhoneForm')">更改</el-button>
        <el-button @click="reset">取 消</el-button>
      </span>
    </el-dialog>
    <el-row>
      <el-col :span="20">
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" :disabled="true"></el-input>
        </el-form-item>
      </el-col>
      <el-button type="primary" @click="emailVisible = true">更改</el-button>
    </el-row>
    <el-dialog
      title="邮箱验证"
      :visible.sync="emailVisible"
      width="30%"
    >
      <el-form
        ref="changeEmailForm"
        class="change-form"
        :model="changeEmailForm"
        :rules="changeEmailRules"
        label-width="80px"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input type="text"
                    v-model="changeEmailForm.email"
                    autocomplete="off"
                    prefix-icon="el-icon-message"
                    placeholder="请输入邮箱号"
                    style="width: 68%"
          ></el-input>
          <el-button type="primary" style="width: 30%" @click="send('changeEmailForm')" :disabled="emailButtonDis">
            {{ buttonName }}
          </el-button>
        </el-form-item>
        <el-form-item label="验证码" prop="validateCode">
          <el-input type="text"
                    v-model="changeEmailForm.validateCode"
                    autocomplete="off"
                    prefix-icon="el-icon-check"
                    placeholder="请输入邮箱中的验证码"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="formSubmit('changeEmailForm')">验证</el-button>
        <el-button @click="reset">取 消</el-button>
      </span>
    </el-dialog>
    <el-alert
      title="邮箱已验证"
      type="success"
      show-icon
      :closable="false"
      style="width: 150px; margin-left: 40px"
      v-if="this.userForm.email!==null">
    </el-alert>
    <el-alert
      title="邮箱未验证"
      type="warning"
      show-icon
      :closable="false"
      style="width: 150px; margin-left: 40px"
      v-if="this.userForm.email===null">
    </el-alert>
  </el-form>
</template>

<script>
export default {
  name: "Info",
  data() {
    var oldPassValidate = (rule, value, callback) => {
      this.$axios.post('/user/checkPassword', {
        id: this.$store.state.id,
        password:this.$md5(this.changePassForm.oldPass)
      }).then(res => {
        if (res.data.data === true) {
          callback()
        }
        else
          callback(new Error('密码错误'))
      }).catch(failRes => {
        callback(new Error('系统错误')+failRes)
      })
    }
    var passwordValidate = (rule, value, callback) => {
      var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[,.#%'+*\-:;^_`0-9A-Za-z]{6,16}$/
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!reg.test(value)) {
        callback(new Error('密码必须为6-16位，必须含有包含数字和英文字母'))
      } else if (this.changePassForm.checkPass !== '') {
        this.$refs.changePassForm.validateField('checkPass');
      }
      callback()
    };
    //自定义的重复密码校验
    var checkPassValidate = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.changePassForm.newPass) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    };
    var phoneValidate = (rule, value, callback) => {
      if(value==='') callback(new Error('请输入电话号码'))
      var phoneReg = /^((13|14|15|16|17|18|19)\d{9})$/
      if (!phoneReg.test(value))
        callback(new Error('请输入正确的手机号码格式'))
      else
        callback()
    };
    var emailValidate = (rule, value, callback) => {
      if (value === '') callback(new Error('请输入邮箱'))
      var reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!reg.test(value))
        callback(new Error('请输入正确的邮箱格式'))
      callback()
    };
    var codeValidate = (rule, value, callback) => {
      if (value === '')
        callback(new Error('请输入验证码'))
      this.$axios.post('/email/check',{
        id:this.$store.state.id,
        code:this.changeEmailForm.validateCode
      }).then(res=>{
        if(res.data.data===true)
          callback()
        else
          callback(new Error('验证码错误'))
      }).catch(failRes=>{
        this.$message.error('系统异常')
        callback()
      })
    };
    return {
      userForm: {
        username: '',
        password: '',
        phone: '',
        email: '',
      },
      changePassForm: {
        oldPass: '',
        newPass: '',
        checkPass: ''
      },
      changePassRules: {
        oldPass: [
          {
            validator: oldPassValidate, trigger: 'blur'
          }
        ],
        newPass: [
          {
            validator: passwordValidate, trigger: 'blur'
          }],
        checkPass: [
          {
            validator: checkPassValidate, trigger: 'blur'
          }],
      },
      changePhoneForm: {
        phone:''
      },
      changePhoneRules: {
        phone:[{
          validator: phoneValidate, trigger:'blur'
        }]
      },
      changeEmailForm: {
        email: '',
        validateCode: ''
      },
      changeEmailRules: {
        email: [{
          validator: emailValidate, trigger: 'blur'
        }],
        validateCode: [
          {
            validator: codeValidate, trigger: 'blur'
          },
          {
            min: 6, max: 6, message: '验证码长度不正确', trigger: 'blur'
          }]
      },

      buttonName: '发送验证码',
      emailButtonDis: false,
      passVisible: false,
      phoneVisible:false,
      emailVisible: false,
    }
  },
  mounted() {
    let url='/user/info/id='+localStorage.getItem('id')
    this.$axios.get(url).then(res=>{
      if(res.data.code===200)
      {
        this.userForm.username=this.$store.state.username
        this.userForm.password=res.data.data.password
        this.userForm.email=res.data.data.email
        this.userForm.phone=res.data.data.phone
      }
    })
  },
  methods: {
    send(formName) {
      const _this=this
      let timerId
      this.$refs[formName].validateField('email', error => {
        if (!error) {
          this.$axios.post('/email/send', {
            id: this.$store.state.id,
            email: this.changeEmailForm.email
          }).then(res => {
            this.$message({
              showClose:true,
              message:'发送成功，有效期5分钟',
              type:'success'
            })
            let count = 60
            _this.changeEmailForm.validateCode=''
            _this.emailButtonDis = true
            _this.buttonName=`${count--}s`
            timerId=window.setInterval(()=>{
              _this.buttonName=`${count--}s`
              if(count<=0)
              {
                window.clearInterval(timerId)
                _this.buttonName='发送验证码'
                _this.emailButtonDis=false
              }
            },1000)
            setTimeout(() => {
              this.emailButtonDis = false
            }, 60000)
          }).catch(failRes => {
              console.log(failRes)
              this.reset()
          })
        } else
          return false
      })
    },
    formSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var pass = this.userForm.password
          var phone = this.userForm.phone
          var email = this.userForm.email
          if (formName === 'changePassForm') {
            pass = this.$md5(this.changePassForm.newPass)
          } else if (formName === 'changeEmailForm') {
            pass=null
            email = this.changeEmailForm.email
          }else{
            pass=null
            phone =this.changePhoneForm.phone
          }
          this.$axios.post('/user/update', {
            id: this.$store.state.id,
            password: pass,
            phone: phone,
            email: email
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.info('修改成功')
              this.userForm.password = pass
              this.userForm.email = email
              this.userForm.phone = phone
              this.reset()
              this.passVisible = false
            } else {
              this.$message.error('修改失败')
              return false
            }
          }).catch(() => {
          })
        } else
          return false
      })
    },
    reset() {
      this.changePassForm.oldPass = ''
      this.changePassForm.newPass = ''
      this.changePassForm.checkPass = ''
      this.changeEmailForm.email = ''
      this.changeEmailForm.validateCode = ''
      this.emailButtonDis = false
      this.passVisible = false
      this.emailVisible = false
    }
  }
}
</script>

<style scoped>
.info-form {
  width: 500px
}

.change-form {
  width: 100%
}

/deep/ .el-form-item__error {
  color: #e6a23c;
  width: 200px;
  display: flex;
  left: 0;
}
</style>
